package com.feicheng.iou.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.feicheng.iou.constant.SessionConstant;
import com.feicheng.iou.entity.Resource;
import com.feicheng.iou.entity.ResourceRecord;
import com.feicheng.iou.entity.Student;
import com.feicheng.iou.pojo.ResourcePOJO;
import com.feicheng.iou.pojo.excelHandle.ExcelPutModel;
import com.feicheng.iou.pojo.login.LoginReturnPOJO;
import com.feicheng.iou.pojo.login.PermissionListPOJO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * @ClassName ExcelListener
 * @Description TODO
 * @Author luoxin
 * @Date 2021/8/2 3:02 下午
 */
@Slf4j  //ExcelExportMapperService
// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
public class ExcelExportMapperService extends AnalysisEventListener<ExcelPutModel> {



    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExportMapperService.class);
    private static int userId ;

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<ExcelPutModel> list = new ArrayList<ExcelPutModel>();
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */

    private ResourceService resourceService;
    private StudentService studentService;
    private ResourceRecordService resourceRecordService;


    public ExcelExportMapperService(ResourceService resourceService,StudentService studentService,ResourceRecordService resourceRecordService,HttpServletRequest request) {
       this.resourceService = resourceService;
       this.studentService = studentService;
       this.resourceRecordService = resourceRecordService;

       LoginReturnPOJO attribute = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);

       userId = attribute.getUser().getUserId();

    }


    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ExcelPutModel data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */


    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());

        //ResourceList
        ArrayList resourceList = new ArrayList();
        //StudentList
        ArrayList studentList = new ArrayList();
        //RecordList
        ArrayList resourceRecordList = new ArrayList();

//        Object attribute = session.getAttribute(SessionConstant.CURRENT);
//        LoginReturnPOJO loginReturnPOJO = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
//        log.info("!!!!!!!!!!!!!!!!"+attribute);


        for (ExcelPutModel excelPutModel : list) {
            ResourcePOJO resourcePOJO = new ResourcePOJO();

            Student student = new Student();
            student.setName(excelPutModel.getName());
            student.setTel(excelPutModel.getTel());
            student.setGraduate(excelPutModel.getGraduate());
            student.setCu(userId);
            //将字符串转换成LocalDateTime类型
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime ldt = LocalDateTime.parse( excelPutModel.getGraduateTime(),df);
            student.setGraduateTime(ldt);
            student.setDegree(excelPutModel.getDegree());
            student.setMajor(excelPutModel.getMajor());
            studentList.add(student);

            Resource resource = new Resource();
            resource.setBz(excelPutModel.getBz());
            resource.setSource(excelPutModel.getSource());
//            resource.setStatu(excelPutModel.getStatu());
            resource.setCsgz(excelPutModel.getCsgz());
            resource.setYpzw(excelPutModel.getYpzw());
            resource.setTdgsmc(excelPutModel.getTdgsmc());
            resource.setCu(userId);
            resourceList.add(resource);

            ResourceRecord resourceRecord = new ResourceRecord();
            resourceRecord.setCu(userId);
            resourceRecordList.add(resourceRecord);


            resourcePOJO.setResource(resource);
            resourcePOJO.setStudent(student);
            resourcePOJO.setResourceRecord(resourceRecord);
            resourceService.insert(resourcePOJO);
        }

        log.info("存储数据库成功！");
    }
}
